#include "lighting.h"

bool lighting::add_light(const light& l)
{
   if(lights.size()+1 >= GL_MAX_LIGHTS)
      return false;
   unsigned size = lights.size();
   for(unsigned i=0; i<size; i++) {
      // a light in this position exists
      if(lights[i].pos==l.pos)
         return false;
   }

   lights.push_back(l);
   //size is still lights.size()-1
   light newl=lights.back();
   glLightfv(GL_LIGHT0+size, GL_AMBIENT, newl.amb);
   glLightfv(GL_LIGHT0+size, GL_DIFFUSE, newl.diff);
   glLightfv(GL_LIGHT0+size, GL_SPECULAR, newl.spec);
   glLightfv(GL_LIGHT0+size, GL_POSITION, newl.pos.pos);
   glEnable(GL_LIGHT0+size);
   return true;
}

bool lighting::del_light(const light::position& pos)
{
   lights_iterator end = lights.end();
   unsigned lidx=0;
   for(lights_iterator it=lights.begin(); it!=end; it++) {
      if((*it).pos == pos) {
         lights.erase(it);
         glDisable(GL_LIGHT0+lidx);
         return true;
      }
      lidx++;
   }
   return false;
}

bool lighting::set_shade_model(GLenum model)
{
   if(model==GL_FLAT || model==GL_SMOOTH) {
      shade_model=model;
      glShadeModel(model);
      return true;
   }
   return false;
}

void lighting::set_global_ambient(const GLfloat* ambient)
{
   glob_amb[0] = ambient[0];
   glob_amb[1] = ambient[1];
   glob_amb[2] = ambient[2];
   glob_amb[3] = ambient[3];
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, glob_amb);
}

void lighting::enable()
{
   glEnable(GL_LIGHTING);
}

void lighting::disable()
{
   glDisable(GL_LIGHTING);
}

bool lighting::enabled()
{
   GLboolean status;
   glGetBooleanv(GL_LIGHTING, &status);
   return (bool)status;
}
